import html2canvas from 'html2canvas'
import i18n from '../plugin/lang/index'

function toImg(el: any) {
  return new Promise((resolve, reject) => {
    html2canvas(el)
      .then((canvas) => {
        resolve(canvas.toDataURL('image/png'))
      })
      .catch(reject)
  })
}

const _tt = {
  /**
   *
   * @param time 时间戳(s | ms) || 格式化时间
   * @param pattern 格式化方案 {y}-{m}-{d} {h}:{i}:{s}
   * @returns 格式化后时间
   */
  parseTime(time: any, pattern?: String) {
    if (arguments.length === 0 || !time) {
      return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
      date = time
    } else {
      if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
        time = parseInt(time)
      } else if (typeof time === 'string') {
        time = time.replace(new RegExp(/-/gm), '/')
      }
      if (typeof time === 'number' && time.toString().length === 10) {
        time = time * 1000
      }
      date = new Date(time)
    }
    class formatObjTyep {
      y!: String | Number
      m!: String | Number
      d!: String | Number
      h!: String | Number
      i!: String | Number
      s!: String | Number
      a!: String | Number
    }
    const formatObj: formatObjTyep = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay(),
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      // @ts-ignore
      let value = formatObj[key]
      // Note: getDay() returns 0 on Sunday
      if (key === 'a') {
        return ['日', '一', '二', '三', '四', '五', '六'][value]
      }
      if (result.length > 0 && value < 10) {
        value = '0' + value
      }
      return value || 0
    })
    return time_str
  },
  /**
   *
   * @param el dom对象
   * @returns
   */
  saveDomToImg(el: any) {
    return new Promise<void>((resolve) => {
      toImg(el).then((url) => {
        if ((window as any).test && (window as any).test.savebase64image) {
          ; (window as any).test.savebase64image(url)
        } else {
          let downloadBtn = document.createElement('a')
          downloadBtn.setAttribute('download', new Date().getTime().toString())
          downloadBtn.setAttribute('href', url as any)
          downloadBtn.click()
        }
        resolve()
      })
    })
  },
  LangSwitch(lang: string) {

    i18n.changeLanguage(lang);
    localStorage.setItem('Lang', lang)
    window.location.reload()
  },

  goBack() {
    window.history.back()
  }

}

export default _tt
